package mspbots.hubspot.data.core.contacts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.hubspot.common.ResultMsg;
import mspbots.hubspot.data.core.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * mspbots.data.sync.autotask.badmessage.BadMessageReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/21
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ContactsReceiver extends BaseReceiver {

    private final ContactsRepository contactsRepository;

    @RabbitListener(queues = "hub-spot.contacts.sync", concurrency = "2")
    public void syncTask(ResultMsg content) {

        Contact contact = Contact.builder().otherId(content.getId()).requestId(content.getRequestId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .email(content.getEntity().findValue("email").textValue())
                .createdTime(LocalDateTime.parse(content.getEntity().get("createdAt").textValue(),
                        DateTimeFormatter.ISO_DATE_TIME))
                .updatedTime(LocalDateTime.parse(content.getEntity().get("updatedAt").textValue(),
                        DateTimeFormatter.ISO_DATE_TIME))
                .entity(content.getEntity())
                .build();

        this.contactsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    contact.setId(ticket.getId());
                    return contact;
                })
                .defaultIfEmpty(contact)
                .flatMap(this.contactsRepository::save)
                .block(Duration.ofSeconds(10));

    }

}
